/**
 * Created by jia on 2015/6/12.
 */
//inside lib
var fs = require('fs')
var http = require('http')
var urllib = require('url')
// outside lib
var jsdom = require('jsdom')
var reqlib = require('request')

var connect = require('connect')
var redis = require('redis')
redis_cli = redis.createClient();
// js
var jquery = fs.readFileSync('../client/js/jquery-2.1.3.min.js', "utf-8")
var server_json = JSON.parse(fs.readFileSync('../server.json'))


app = connect()
app.use('/api/js/ele_me_restaurant_spider', function(req, res) {

    var url_parse = urllib.parse(req.url, true)
    var spider_url = decodeURIComponent(url_parse['query']['url'])
    var sprider_json_url = spider_url+'/userinfo'

    reqlib(sprider_json_url, function(err, response, body){
        if(!err && response.statusCode==200){
            var url_data = {}
            var userinfo = JSON.parse(body)
            url_data['least_deliver'] = userinfo['data']['deliverAmount']
            jsdom.env({
                url: spider_url,
                src: [jquery],
                done: function(error, window){
                    if(error){
                        throw error;
                    }
                    var $ = window.$

                    $('#rst_aside ul li i').each(function(){
                        if ($(this).text() == '减'){

                            var discount_text = $(this).parent().text()
                            var discount_list = discount_text.split('，')
                            for(var i =0; i != discount_list.length; ++i) {
                                discount_list[i] = discount_list[i].split(/[^\d]+/ig).slice(1,3)
                                for(var j = 0; j != discount_list[i].length;++j){
                                    discount_list[i][j] = Number(discount_list[i][j])
                                }
                            }
                            discount_list.sort(function(a,b) {return b[1] - a[1]})
                            url_data['discount'] = discount_list
                        }
                    })
                    url_data['shop_name'] = $('.rst-name').text()
                    console.log(JSON.stringify(url_data))
                    redis_cli.hset('ele-shops', spider_url, JSON.stringify(url_data))
                    res.end('yes')
                }
            })
        }
    })

});

http.createServer(app).listen(server_json['nodejs_port'], '0.0.0.0')